package com.qf.blog.controller;

import com.qf.blog.entity.User;
import com.qf.blog.exception.BlogException;
import com.qf.blog.service.impl.LikeService;
import com.qf.blog.service.impl.PostScoreService;
import com.qf.blog.utils.Result;
import com.qf.blog.vo.LikeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.HttpServerErrorException;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/like")
public class LikeController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private LikeService likeService;

    @Autowired
    private PostScoreService postScoreService;

    @PostMapping("/clickLike")
    @ResponseBody
    public Result clickLike(@RequestBody LikeVo likeVo, HttpSession session) {

        // 1.判断用户是否登录
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            throw new BlogException(1003, "请先登录");
        }

        // 2.判断当前用户是否已经点赞
        boolean isLike = likeService.isLike(likeVo.getEntityId(), likeVo.getEntityType(), loginUser.getId());
        if (isLike) {

            // a、给帖子取消的点赞
            likeService.removeLike(likeVo.getEntityId(), likeVo.getEntityType(), loginUser.getId());

            // b、给帖子作者的赞数量-1
            likeService.likeUserDecr(likeVo.getEntityUserId());

        } else {
            // a、给帖子点赞
            likeService.addLike(likeVo.getEntityId(), likeVo.getEntityType(), loginUser.getId());

            // b、给帖子作者的赞数量+1
            likeService.likeUserIncr(likeVo.getEntityUserId());
        }

        // 3、查询最新的点赞数量
        Long size = likeService.likeSize(likeVo.getEntityId(), likeVo.getEntityType());


        if (likeVo.getEntityType() == 1) {
            // 如果给帖子点赞了或者取消点赞了，都需要去计算你帖子的分数
            postScoreService.addPostToRedis(likeVo.getEntityId());
        }

        Map<String, Object> map = new HashMap<>();
        map.put("likeCount", size);
        map.put("likeStatus", isLike ? 0 : 1);
        return Result.ok(map);
    }
}
